/*
 * SplashActivity.java
 *
 * Copyright(c) IronOne Technologies (Pvt) Ltd.  All Rights Reserved.
 * This software is the proprietary information of IronOne Technologies (Pvt) Ltd.
 *
 */
package com.ironone.streaming;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.SessionState;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.comm.NetworkCheck;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.lite.R;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.ResponseDataModel;

/**
 * { This class shows the splash screen for the user }
 * 
 * @Created on May 22, 2014 : 11:50:00 AM
 * @author Suren Manawatta
 */
public class SplashActivity extends Activity implements AnimationListener{
        TextView errorTextView;
        ImageButton retryButton_flame;
        ImageButton retryButton_circle;
        LinearLayout left_anim_layout, right_anim_layout;

        /*ImageView boarding_drop_ImageView;
        ImageView matrix_drop_imageView1;
        ImageView matrix_drop_imageView11;
        ImageView matrix_drop_imageView2;
        ImageView matrix_drop_imageView22;
        ImageView matrix_drop_imageView3;
        ImageView matrix_drop_imageView33;
        ImageView matrix_drop_imageView4;
        ImageView matrix_drop_imageView44;
        ImageView matrix_line_imageView;*/

        /*Animation leftRight;
        Animation updown;
        Animation updownMartix1;
        Animation updownMartix11;
        Animation updownMartix2;
        Animation updownMartix22;
        Animation updownMartix3;
        Animation updownMartix33;
        Animation updownMartix4;
        Animation updownMartix44;*/

        private Handler handler;
        Runnable runnable;

        ImageView imageLeft, imageRight;
        Animation animLeft, animRight;
        
        ImageView lite_logo;

        // xmlData used in RadioPlayer.java file
        // static String xmlData;
        private static boolean showWiFiInfoMessage = false;
        private static boolean isFacebookLoggedIn = false;
        private static int waitingTimeInMiliseconds = 3000;
        int upDownAnimeSpeed = 900;
        int randomNo = 0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                try {
                        super.onCreate(savedInstanceState);
                        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
                        handler = new Handler();
                        setContentView(R.layout.litefm_splash2);
                       
                        
                        //LiteFM logo
                        /*int scrnWidth = FormObject.getInstance().getScreenWidth();
            			int supWidth = (int)((scrnWidth * 0.6));
            			int scrnHeight = FormObject.getInstance().getScreenHeight();
             			int supHeight = (int)((scrnHeight * 0.6));
             			lite_logo=(ImageView) findViewById(R.id.lite_logo);
             			RelativeLayout.LayoutParams logoParam = (RelativeLayout.LayoutParams) lite_logo.getLayoutParams();
            			logoParam.width = (int) (scrnWidth * 0.6);
            			logoParam.height = (int) (scrnHeight * 0.1);
            			lite_logo.setLayoutParams(logoParam);*/

                        /* Create Animation */
                        imageLeft = (ImageView) findViewById(R.id.imageViewLeft);
                        
                        imageRight = (ImageView) findViewById(R.id.imageViewRight);

                        animRight = AnimationUtils.loadAnimation(getApplicationContext(),
                                        R.anim.load_anim);
                        animLeft = AnimationUtils.loadAnimation(getApplicationContext(),
                                        R.anim.load_anim);
                        left_anim_layout=(LinearLayout) findViewById(R.id.left_anim_layout);
                        right_anim_layout=(LinearLayout) findViewById(R.id.right_anim_layout);
                        
                        animRight.setAnimationListener(this);
                        animLeft.setAnimationListener(this);

                        /*animRight.setAnimationListener(new AnimationListener() {

                                @Override
                                public void onAnimationStart(Animation animation) {
                                        // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {
                                        // TODO Auto-generated method stub
                                        // imageRight.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                        // TODO Auto-generated method stub
                                        // imageRight.setVisibility(View.INVISIBLE);
                                		//Log.e("Animation", "right on end");
                                        //imageLeft.startAnimation(animLeft);
                                }
                        });

                        animLeft.setAnimationListener(new AnimationListener() {

                                @Override
                                public void onAnimationStart(Animation animation) {
                                        // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {
                                        // TODO Auto-generated method stub
                                        // imageRight.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                        // TODO Auto-generated method stub
                                        // imageRight.setVisibility(View.INVISIBLE);
                                		//Log.e("Animation", "left on end");
                                        //imageRight.startAnimation(animRight);
                                }
                                
                        });*/

                        imageRight.startAnimation(animRight);
                        //imageLeft.startAnimation(animLeft);

                        errorTextView = (TextView) findViewById(R.id.errorTextView);
                        errorTextView.setVisibility(View.INVISIBLE);

                        retryButton_flame = (ImageButton) findViewById(R.id.retryButton_flame);
                        retryButton_circle = (ImageButton) findViewById(R.id.retryButton_circle);

                        retryButton_flame.setVisibility(View.INVISIBLE);
                        retryButton_circle.setVisibility(View.INVISIBLE);

                        retryButton_circle.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        handler.removeCallbacks(runnable);

					//imageRight.clearAnimation();
					errorTextView.setVisibility(View.INVISIBLE);

                                        /* Create Animation */
                                        Animation rotation = AnimationUtils.loadAnimation(
                                                        getApplicationContext(), R.anim.rotate_button);
                                        rotation.setRepeatCount(Animation.INFINITE);
                                        /* Start Animation */
                                        retryButton_circle.startAnimation(rotation);
                                        retryButton_circle.setEnabled(false);

                                        // new DisplyRetryProgressRingAsync().execute();
                                        new CommonAsync().execute(1);
                                }
                        });

                        // These2 functions called only once. return values
                        // goes to FO and reused until app closed
                        MainApplication.getScreenDimensions(this);
                        MainApplication.getScreenTextSize(this);

                        new CommonAsync().execute(3);

                } catch (Exception e) {
                        CustomAlertDialog alertDialog = new CustomAlertDialog(this,
                                        CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
                        alertDialog.setTitleText(getString(R.string.what_the_duck_));
                        //alertDialog.setMessageText(getString(R.string.something_snapped));
                        alertDialog.show();
                }
        }

        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
                try {
                        super.onWindowFocusChanged(hasFocus);

                        if (!hasFocus)
                                return;

                        LinearLayout.LayoutParams params = (LayoutParams) retryButton_flame
                                        .getLayoutParams();
                        params.width = (int) (FormObject.getInstance().getScreenWidth() / 10);
                        params.height = params.width;
                        retryButton_flame.setLayoutParams(params);
                        retryButton_circle.setLayoutParams(params);
                } catch (Exception e) {
                }
        }

        /*int animeDuration1 = 1400;
        int animeDuration2 = 2400;
        int animeDuration3 = 2000;
        int animeDuration4 = 1000;

        private void animeCommon() {
                try {
                        updownMartix1.setDuration(animeDuration1);
                        matrix_drop_imageView1.setVisibility(View.VISIBLE);
                        matrix_drop_imageView1.startAnimation(updownMartix1);

                        updownMartix2.setDuration(animeDuration2);
                        matrix_drop_imageView2.setVisibility(View.VISIBLE);
                        matrix_drop_imageView2.startAnimation(updownMartix2);

                        updownMartix3.setDuration(animeDuration3);
                        matrix_drop_imageView3.setVisibility(View.VISIBLE);
                        matrix_drop_imageView3.startAnimation(updownMartix3);

                        updownMartix4.setDuration(animeDuration4);
                        matrix_drop_imageView4.setVisibility(View.VISIBLE);
                        matrix_drop_imageView4.startAnimation(updownMartix4);

                        handler.removeCallbacks(runnable);

                        handler.postDelayed(runnable = new Runnable() {
                                @Override
                                public void run() {
                                        updownMartix11.setDuration(animeDuration1);
                                        matrix_drop_imageView11.setVisibility(View.VISIBLE);
                                        matrix_drop_imageView11.startAnimation(updownMartix11);
                                }
                        }, (animeDuration1 / 2));

                        handler.postDelayed(runnable = new Runnable() {
                                @Override
                                public void run() {
                                        updownMartix22.setDuration(animeDuration2);
                                        matrix_drop_imageView22.setVisibility(View.VISIBLE);
                                        matrix_drop_imageView22.startAnimation(updownMartix22);
                                }
                        }, (animeDuration2 / 2));

                        handler.postDelayed(runnable = new Runnable() {
                                @Override
                                public void run() {
                                        updownMartix33.setDuration(animeDuration3);
                                        matrix_drop_imageView33.setVisibility(View.VISIBLE);
                                        matrix_drop_imageView33.startAnimation(updownMartix33);
                                }
                        }, (animeDuration3 / 2));

                        handler.postDelayed(runnable = new Runnable() {
                                @Override
                                public void run() {
                                        updownMartix44.setDuration(animeDuration4);
                                        matrix_drop_imageView44.setVisibility(View.VISIBLE);
                                        matrix_drop_imageView44.startAnimation(updownMartix44);
                                }
                        }, (animeDuration4 / 2));
                } catch (Exception e) {
                        CustomAlertDialog alertDialog = new CustomAlertDialog(this,
                                        CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
                        alertDialog.setTitleText(getString(R.string.what_the_duck_));
                        alertDialog.setMessageText(getString(R.string.something_snapped));
                        alertDialog.show();
                }
        }*/

        public static boolean networkOk = false;

        public class CommonAsync extends AsyncTask<Integer, Void, Integer> {

                @Override
                protected Integer doInBackground(Integer... arg0) {
                        try {
                                int inc = 0;
                                while (inc < arg0[0]) {
                                        inc++;
                                        if (NetworkCheck
                                                        .isNetworkAvailable(getApplicationContext())) {
                                                networkOk = true;
                                                break;
                                        } else {
                                                try {
                                                        Thread.sleep(waitingTimeInMiliseconds);
                                                } catch (InterruptedException e) {
                                                        e.printStackTrace();
                                                }
                                        }
                                }
                        } catch (Exception e) {
                        }
                        return arg0[0];
                }
                @Override
                protected void onPostExecute(Integer retryCount) {
                        try {
                                if (networkOk) {
                                        if (NetworkCheck.getNetworkType(SplashActivity.this) != 1) {
                                                // errorTextView.setText(R.string._enable_wi_fi_info_message);
                                                // errorTextView.setVisibility(View.VISIBLE);
                                                // TODO: custom toast
                                                Toast.makeText(SplashActivity.this,
                                                                R.string._enable_wi_fi_info_message,
                                                                Toast.LENGTH_LONG).show();
                                                showWiFiInfoMessage = true;
                                        }

                                        // Start Facebook Login
                                        Session.openActiveSession(SplashActivity.this, false,
                                                        new Session.StatusCallback() {
                                                                // Callback when session changes state
                                                                @Override
                                                                public void call(Session session,
                                                                                SessionState state, Exception exception) {
                                                                        if (state.isOpened()) {
                                                                                isFacebookLoggedIn = true;
                                                                                FormObject.getInstance()
                                                                                                .setFbLoginStatus(true);
                                                                        }
                                                                }
                                                        });

                                        // initDataManager = new
                                        // InitDataManager(SplashActivity.this);

                                        // Toast.makeText(SplashActivity.this,
                                        // FormObject.getInstance().getDataVersion()+" daver",
                                        // Toast.LENGTH_LONG).show();

                                        new SplashAsync().execute();
                                } else {
                                        //imageRight.clearAnimation();
                                		left_anim_layout.setVisibility(View.INVISIBLE);
                                		right_anim_layout.setVisibility(View.INVISIBLE);

                                        retryButton_circle.setEnabled(true);
                                        retryButton_circle.setVisibility(View.VISIBLE);
                                        retryButton_circle.clearAnimation();
                                        errorTextView.setVisibility(View.VISIBLE);
                                        retryButton_flame.setVisibility(View.INVISIBLE);
                                        showWiFiInfoMessage = false;

                                        handler.removeCallbacks(runnable);
                                }
                        } catch (Exception e) {
                                CustomAlertDialog alertDialog = new CustomAlertDialog(
                                                SplashActivity.this, CusAlrtBtnTypes.OK,
                                                CusAlrtIconTypes.DUCK);
                                alertDialog.setTitleText(getString(R.string.what_the_duck_));
                                //alertDialog.setMessageText(getString(R.string.something_snapped));
                                alertDialog.show();
                        }
                }
        }

        public static boolean initSuccess = false;

        public class SplashAsync extends AsyncTask<String, Void, String> {

                @Override
                protected String doInBackground(String... params) {
                        try {
                                // xmlData = initDataManager.getXML().trim();
                                HTTPManager httpmanager = new HTTPManager(SplashActivity.this);
                                ResponseDataModel responseModel = httpmanager
                                                .getInitServiceData();

                                if (responseModel.isError && responseModel.responseData == null) {
                                        return responseModel.errorMessage;
                                }

                                if (ModelMapper.getGeneralDataModel(responseModel) == null) {
                                        return getString(R.string.error_jsonexception);
                                } else {
                                        initSuccess = true;
                                        MainApplication.foSaveChanges(SplashActivity.this);
                                }

                                // ShowMessage : This will wait few seconds so user can read the
                                // Wi-Fi info message
                                if (!responseModel.isError && showWiFiInfoMessage) {
                                        try {
                                                Thread.sleep(waitingTimeInMiliseconds);
                                        } catch (InterruptedException e) {
                                                e.printStackTrace();
                                        }
                                }
                        } catch (Exception e) {
                                return getString(R.string.error_general);
                        }
                        return null;
                }

                @Override
                protected void onPostExecute(String data) {
                        try {
                                Intent i = null;

                                if (initSuccess) {
                                        if (isFacebookLoggedIn) {
                                                i = new Intent(SplashActivity.this,
                                                                RadioPlayerActivity.class);
                                        } else {
                                                i = new Intent(SplashActivity.this,
                                                                InitLoginActivity.class);
                                        }
                                        startActivity(i);
                                        finish();
                                } else {
                                		left_anim_layout.setVisibility(View.INVISIBLE);
                                		right_anim_layout.setVisibility(View.INVISIBLE);
                                        retryButton_circle.setEnabled(true);
                                        retryButton_circle.setVisibility(View.VISIBLE);
                                        retryButton_circle.clearAnimation();
                                        errorTextView.setText(R.string.splash_retry);
                                        errorTextView.setVisibility(View.VISIBLE);
                                        retryButton_flame.setVisibility(View.INVISIBLE);
                                        showWiFiInfoMessage = false;

                                        handler.removeCallbacks(runnable);
                                        
                                        //imageRight.clearAnimation();
                                        Thread.sleep(300);

                                        if (data == null || data.equals(""))
                                                data = getString(R.string.error_general);

                                        CustomAlertDialog alertDialog = new CustomAlertDialog(
                                                        SplashActivity.this, CusAlrtBtnTypes.OK,
                                                        CusAlrtIconTypes.WIZERD);
                                        /*alertDialog.setTitleText(getString(R.string.you_shall_not_pass));
                                        alertDialog.setMessageText(data);*/
                                        alertDialog.setTitleText(data);
                                        alertDialog.show();
                                }
                        } catch (Exception e) {
                                CustomAlertDialog alertDialog = new CustomAlertDialog(
                                                SplashActivity.this, CusAlrtBtnTypes.OK,
                                                CusAlrtIconTypes.DUCK);
                                alertDialog.setTitleText(getString(R.string.what_the_duck_));
                                //alertDialog.setMessageText(getString(R.string.something_snapped));
                                alertDialog.show();
                        }
                }
        }

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			if(animation.equals(animRight)){
				imageLeft.setVisibility(View.VISIBLE);
				imageLeft.startAnimation(animLeft);
			}else{
				imageRight.startAnimation(animRight);
			}
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub
			/*if(animation.equals(animRight)){
				imageLeft.startAnimation(animLeft);
				Log.e("3", "xxxxxxxxxxxxxxx");
			}else{
				imageRight.startAnimation(animRight);
				Log.e("4", "xxxxxxxxxxxxxxx");
			}*/
			
		}

		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
			
			
		}
}

